package org.example.testdemo.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import org.example.testdemo.pojo.PageReq;
import org.example.testdemo.pojo.User;
import org.example.testdemo.pojo.combination.UserInformation;
import org.example.testdemo.service.UserService;
import org.example.testdemo.tool.ApiResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@Validated
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("logon")
    public ApiResponse logon(String username, String password, HttpServletRequest request){
        //利用用户名获取用户信息
        User findined = userService.findinUsername(username);
        if(findined==null){
            return ApiResponse.fail(20002,"登录失败，请检查账号或密码是否正确");
        }
        //匹配密码是否一致
        String  encryptNewPwd = MD5.create().setSalt(findined.getSecretKey().getBytes()).digestHex(password);
        if(!encryptNewPwd.equals(findined.getPassword())){
            return ApiResponse.fail(20002,"登录失败，请检查账号或密码是否正确");
        }
        //将信息保存到session中
        HttpSession session = request.getSession();
        session.setAttribute("userId",findined.getUserId());
        session.setAttribute("bCode",findined.getBCode());
        session.setAttribute("permissionId",findined.getPermissionId());
        //返回用户姓名
        Map<String,Object> map = new HashMap<>();
        map.put("name",findined.getName());
        map.put("permissionId",findined.getPermissionId());
        return ApiResponse.success(map);
    }

    @PostMapping("logonOut")
    public ApiResponse logonOut(HttpServletRequest request){
        request.getSession().invalidate();
        return ApiResponse.success();
    }

    @PostMapping("getUser")
    public ApiResponse getUser(String name,String department,PageReq req){
        if(name==null || name.isEmpty()){
            name = null;
        }
        if(department==null || department.isEmpty()){
            department = null;
        }
        IPage<UserInformation> userServiceUser = userService.getUser(name, department, req);
        return ApiResponse.success(userServiceUser);
    }

    @PostMapping("getUserExclude")
    public ApiResponse getUserExclude(String name, @NotNull(message = "参数异常") String department,  @NotNull(message = "参数异常")String projectId, PageReq req){
        if(name==null || name.isEmpty()){
            name = null;
        }
        return ApiResponse.success(userService.getUserExclude(name,department,projectId,req));
    }
}
